package com.example.yunifang;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.yunifang.adapter.ClassSerachHistoryAdapter;
import com.example.yunifang.db.SerachHistorySqlliteOpenHelper;

@SuppressLint("NewApi")
public class ClassSeachActivity extends Activity {

	public static ListView serach_hestory;
	private List<String> alllist;
	private List<String> alllistad;
	private ClassSerachHistoryAdapter serachHistoryAdapter;
	public TextView serach_tt;
	private EditText serach_edit;
	private int count;
	public static TextView serach_hestory_bt;
	private SerachHistorySqlliteOpenHelper serachHistory;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_class_seach);
		serach_edit = (EditText) findViewById(R.id.serach_edit);
		serach_hestory = (ListView) findViewById(R.id.serach_hestory);
		serach_tt = (TextView) findViewById(R.id.serach_tt);
		serach_hestory_bt = (TextView) findViewById(R.id.serach_hestory_bt);
		// 实例化数据库类
		serachHistory = new SerachHistorySqlliteOpenHelper(this);
		// 对edittext进行监听 获取文本改变状态
		serach_edit.addTextChangedListener(watcher);
		// 对取消和搜索键进行监听
		AllLisTen();
		// 对数据库进行查询进行listview的显示
		GetDB();
		serach_hestory_bt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String str = serach_hestory_bt.getText().toString().trim();
				if (str.equals("显示全部历史")) {
					Toast.makeText(ClassSeachActivity.this, "显示", 0).show();
					count = alllistad.size();
					GetAdApter();
					serach_hestory_bt.setText("清除全部历史");
				} else {
					alllistad.clear();
					count=0;
					SQLiteDatabase alldel = serachHistory.getReadableDatabase();
					alldel.delete(SerachHistorySqlliteOpenHelper.SQLITE_TABLE, null, null);
					GetAdApter();
					serach_hestory_bt.setText("");
				}
			}
		});

	}

	public void GetDB() {

		SQLiteDatabase allreadableDatabase = serachHistory
				.getReadableDatabase();
		Cursor allquery = allreadableDatabase.query(false,
				SerachHistorySqlliteOpenHelper.SQLITE_TABLE, null, null, null,
				null, null, null, null, null);

		// 存放数据的集合
		alllist = new ArrayList<String>();
		alllistad = new ArrayList<String>();
		alllistad.clear();
		alllist.clear();
		while (allquery.moveToNext()) {
			String allstr = allquery.getString(allquery
					.getColumnIndex("serach_str"));

			alllist.add(allstr);

		}

		for (int i = alllist.size() - 1; i >= 0; i--) {
			alllistad.add(alllist.get(i));
		}
		if(alllistad.size()<1)
		{
			serach_hestory_bt.setVisibility(View.GONE);
		}else{
			serach_hestory_bt.setVisibility(View.VISIBLE);
		}
		if (alllistad.size() >= 0) {

			if (serachHistoryAdapter == null) {
				if (alllistad.size() > 4) {
					count = 3;
					serach_hestory_bt.setText("显示全部历史");
				} else {
					count = alllist.size();
					serach_hestory_bt.setText("清除全部历史");
				}

				GetAdApter();
			} else {
				serachHistoryAdapter.notifyDataSetChanged();
			}
		}
	}

	public void GetAdApter() {
		serachHistoryAdapter = new ClassSerachHistoryAdapter(this, alllistad, count);
		serach_hestory.setAdapter(serachHistoryAdapter);
	}

	private void AllLisTen() {
		serach_tt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String serach_edit_str = serach_edit.getText().toString()
						.trim();
				int length = serach_edit_str.length();
				if (length > 0) {
					SQLiteDatabase queryreadableDatabase = serachHistory
							.getReadableDatabase();
					Cursor query = queryreadableDatabase.query(false,
							serachHistory.SQLITE_TABLE, null, "serach_str=?",
							new String[] { serach_edit_str + "" }, null, null,
							null, null, null);
					if (query.moveToNext()) {
						int ids = query.getInt(query.getColumnIndex("_id"));
						SQLiteDatabase delreadableDatabase = serachHistory
								.getReadableDatabase();
						delreadableDatabase.delete(serachHistory.SQLITE_TABLE,
								"_id=?", new String[] { ids + "" });
						SQLiteDatabase addreadableDatabase = serachHistory
								.getReadableDatabase();
						ContentValues values = new ContentValues();
						values.put("serach_str", serach_edit_str);
						addreadableDatabase.insert(serachHistory.SQLITE_TABLE,
								null, values);
					} else {
						SQLiteDatabase addreadableDatabase = serachHistory
								.getReadableDatabase();
						ContentValues values = new ContentValues();
						values.put("serach_str", serach_edit_str);
						addreadableDatabase.insert(serachHistory.SQLITE_TABLE,
								null, values);
					}

				} else {
					finish();
					overridePendingTransition(R.anim.infragment, R.anim.outfragment);
				}

			}
		});
	}

	private TextWatcher watcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			if (s.length() > 0) {
				serach_tt.setText("搜索");
			} else {
				serach_tt.setText("取消");
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub

		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			int lines = serach_edit.getLineCount();
			// 限制最大输入行数
			// if (lines > 1) {
			// String str = s.toString();
			// int cursorStart = serach_edit.getSelectionStart();
			// int cursorEnd = serach_edit.getSelectionEnd();
			// if (cursorStart == cursorEnd && cursorStart < str.length() &&
			// cursorStart >= 1) {
			// str = str.substring(0, cursorStart-1) +
			// str.substring(cursorStart);
			// } else {
			// str = str.substring(0, s.length()-1);
			// }
			// // setText会触发afterTextChanged的递归
			// serach_edit.setText(str);
			// // setSelection用的索引不能使用str.length()否则会越界
			// serach_edit.setSelection(serach_edit.getText().length());
			// }
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.class_seach, menu);
		return true;
	}

}
